import React, { useEffect, useState, useRef, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  SafeAreaView,
  TouchableOpacity,
  Image,
  TextInput,
  FlatList,
  RefreshControl,
  StatusBar,
  Platform,
  Modal,
  Dimensions,
  ActivityIndicator,
} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { getStatusBarHeight } from '../../utils/statusBarHeight';
import { Toast } from '@ant-design/react-native';
import { logoutApi, searchWorkOrderApi, getBatchOrderListApi } from './api';
import outlogin from '../../assets/outlogin.png';
import zwsj from '../../assets/zwsj.png';
import zwtp from '../../assets/zwtp.png';

interface WorkFlowScreenProps {
  onLogout: () => void;
  navigation?: any;
}

const WorkFlowScreen: React.FC<WorkFlowScreenProps> = ({ onLogout, navigation }) => {
  const [keyword, setKeyword] = useState('');
  const [loading, setLoading] = useState(false);
  const [loadingMore, setLoadingMore] = useState(false);
  const [workOrders, setWorkOrders] = useState<any[]>([]);
  const [hasSearched, setHasSearched] = useState(false);
  const [refreshing, setRefreshing] = useState(false);
  const [current, setCurrent] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [expandedItems, setExpandedItems] = useState<Set<number>>(new Set());
  const [batchData, setBatchData] = useState<{ [key: string]: any[] }>({});
  const [imagePreviewVisible, setImagePreviewVisible] = useState(false);
  const [previewImageUrl, setPreviewImageUrl] = useState<string>('');

  // 防抖相关
  const loadMoreTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const isLoadMoreTriggered = useRef(false);

  // 组件卸载时清理定时器
  useEffect(() => {
    return () => {
      if (loadMoreTimeoutRef.current) {
        clearTimeout(loadMoreTimeoutRef.current);
      }
    };
  }, []);

  // 搜索工单函数
  const searchWorkOrders = async (searchKeyword?: string, page: number = 1, isRefresh: boolean = false) => {
    if (page === 1) {
      setLoading(true);
      // 如果是第一页搜索，重置展开状态和加载更多状态
      if (searchKeyword || isRefresh) {
        setExpandedItems(new Set());
        setBatchData({});
        isLoadMoreTriggered.current = false;
        // 清除加载更多的防抖定时器
        if (loadMoreTimeoutRef.current) {
          clearTimeout(loadMoreTimeoutRef.current);
        }
      }
    } else {
      setLoadingMore(true);
    }

    try {
      const params = {
        current: page,
        size: 10,
        ...(searchKeyword && { keyword: searchKeyword }),
      };
      console.log('请求接口: /app/WorkOrder/searchWorkOrder', params);
      const res = await searchWorkOrderApi(params);
      console.log('搜索工单接口返回:', res);

      // 处理返回数据
      if (res && res.data) {
        const newRecords = res.data.records || res.data || [];
        if (page === 1 || isRefresh) {
          setWorkOrders(newRecords);
        } else {
          setWorkOrders(prev => [...prev, ...newRecords]);
        }

        // 判断是否还有更多数据
        const total = res.data.total || 0;
        const totalPages = Math.ceil(total / 10);
        setHasMore(page < totalPages);
      } else {
        if (page === 1) {
          setWorkOrders([]);
        }
      }
      setCurrent(page);
      setHasSearched(true);
    } catch (e: any) {
      console.log('搜索工单接口异常:', e);
      if (page === 1) {
        setWorkOrders([]);
      }
      setHasSearched(true);
    } finally {
      setLoading(false);
      setLoadingMore(false);
      setRefreshing(false);
    }
  };

  // 下拉刷新
  const onRefresh = async () => {
    setRefreshing(true);
    // 清空搜索条件
    setKeyword('');
    // 重置展开状态
    setExpandedItems(new Set());
    // 清空批次数据
    setBatchData({});
    await searchWorkOrders('', 1, true);
  };

  // 触底加载更多 - 带防抖
  const onLoadMore = useCallback(() => {
    // 如果正在加载或没有更多数据，直接返回
    if (loading || loadingMore || !hasMore || isLoadMoreTriggered.current) {
      return;
    }

    // 清除之前的定时器
    if (loadMoreTimeoutRef.current) {
      clearTimeout(loadMoreTimeoutRef.current);
    }

    // 设置防抖定时器
    loadMoreTimeoutRef.current = setTimeout(async () => {
      if (!loading && !loadingMore && hasMore && !isLoadMoreTriggered.current) {
        isLoadMoreTriggered.current = true;
        try {
          await searchWorkOrders(keyword, current + 1);
        } finally {
          isLoadMoreTriggered.current = false;
        }
      }
    }, 300); // 300ms防抖延迟
  }, [loading, loadingMore, hasMore, keyword, current]);

  // 页面加载时调用搜索工单接口
  useEffect(() => {
    searchWorkOrders();
  }, []);

  // 获取批次列表
  const handleGetBatchOrderList = async (workOrderId: string, index: number) => {
    try {
      const params = {
        work_order_id: workOrderId,
      };
      console.log('请求批次接口: /app/BatchOrder/getBatchOrderList', params);
      const res = await getBatchOrderListApi(params);
      console.log('批次接口返回:', res);

      // 更新批次数据
      setBatchData(prev => ({
        ...prev,
        [workOrderId]: res.data || []
      }));

      // 切换展开状态
      setExpandedItems(prev => {
        const newSet = new Set(prev);
        if (newSet.has(index)) {
          newSet.delete(index);
        } else {
          newSet.add(index);
        }
        return newSet;
      });
    } catch (e: any) {
      console.log('获取批次列表接口异常:', e);
      Toast.fail(e.message || '获取批次列表失败', 1);
    }
  };

  // 图片预览相关函数
  const handleImagePreview = (imageUrl: string) => {
    setPreviewImageUrl(imageUrl);
    setImagePreviewVisible(true);
  };

  const closeImagePreview = () => {
    setImagePreviewVisible(false);
    setPreviewImageUrl('');
  };

  // 渲染工单项
  const renderWorkOrderItem = ({ item, index }: { item: any; index: number }) => (
    <View style={styles.listItem}>
      {/* 顶部信息 */}
      <View style={styles.itemHeader}>
        <Text style={styles.itemLabel}>单号：</Text>
        <Text style={styles.itemValue}>{item.work_order_num || '-'}</Text>
      </View>
      <View style={styles.itemHeader}>
        <Text style={styles.itemLabel}>销售单号：</Text>
        <Text style={styles.itemValue}>{item.sales_order_num || '-'}</Text>
      </View>

      {/* 中间信息 - 带图片 */}
      <View style={styles.itemMiddle}>
        <TouchableOpacity
          onPress={() => handleImagePreview(item.product_link || '')}
          activeOpacity={0.8}
        >
          <Image
            source={item.product_link ? { uri: item.product_link } : zwtp}
            style={styles.productImage}
          />
        </TouchableOpacity>
        <View style={styles.itemInfo}>
          <View style={styles.itemRow}>
            <Text style={styles.itemLabel}>产品编码：</Text>
            <Text style={styles.itemValue}>{item.product_encode || '-'}</Text>
          </View>
          <View style={styles.itemRow}>
            <Text style={styles.itemLabel}>数量：</Text>
            <Text style={styles.itemValue}>{item.quantity || '-'}</Text>
          </View>
        </View>
      </View>

      {/* 底部展开按钮 */}
      <TouchableOpacity
        style={styles.expandButton}
        onPress={() => handleGetBatchOrderList(item.id || item.work_order_id, index)}
      >
        <Text style={styles.expandText}>
          {expandedItems.has(index) ? '收起批次' : '展开批次'}
        </Text>
      </TouchableOpacity>

      {/* 批次列表 */}
      {expandedItems.has(index) && batchData[item.id || item.work_order_id] && (
        <View style={styles.batchContainer}>
          <Text style={styles.batchTitle}>批次列表：</Text>
          {batchData[item.id || item.work_order_id].map((batch: any, batchIndex: number) => (
            <TouchableOpacity
              key={batchIndex}
              style={styles.batchItem}
              onPress={() => {
                console.log('点击批次项:', batch);
                console.log('批次ID:', batch.id);
                console.log('navigation对象:', navigation);

                // 这里需要根据您的导航配置来跳转
                // 假设您使用的是 React Navigation
                if (navigation) {
                  console.log('准备跳转到批次详情页面');
                  navigation.navigate('BatchDetail', { id: batch.id });
                } else {
                  console.log('navigation对象不存在');
                  // 如果没有navigation，可以尝试其他方式
                  Toast.info('导航功能暂不可用', 1);
                }
              }}
            >
              <View style={styles.batchRow}>
                <Text style={styles.batchLabel}>批次号：</Text>
                <Text style={styles.batchValue}>{batch.batch_order_num || '-'}</Text>
              </View>
              <View style={styles.batchRow}>
                <Text style={styles.batchLabel}>交期：</Text>
                <Text style={styles.batchValue}>{batch.delivery_date || '-'}</Text>
              </View>
              <View style={styles.batchRow}>
                <Text style={styles.batchLabel}>数量：</Text>
                <Text style={styles.batchValue}>{batch.quantity ?? '-'}</Text>
              </View>
            </TouchableOpacity>
          ))}
          {batchData[item.id || item.work_order_id].length === 0 && (
            <Text style={styles.noBatchText}>暂无批次数据</Text>
          )}
        </View>
      )}
    </View>
  );

  // 渲染底部加载更多
  const renderFooter = () => {
    if (loadingMore) {
      return (
        <View style={styles.loadingMore}>
          <ActivityIndicator size="small" color="#007AFF" />
          <Text style={styles.loadingText}>加载中...</Text>
        </View>
      );
    }
    if (!hasMore && workOrders.length > 0) {
      return (
        <View style={styles.loadingMore}>
          <Text style={styles.loadingText}>没有更多数据了</Text>
        </View>
      );
    }
    return null;
  };

  // 退出登录
  const handleLogout = async () => {
    try {
      // 调用退出登录接口
      const res = await logoutApi();
      console.log('退出登录接口返回:', res);
      // 清除本地存储的token
      await AsyncStorage.removeItem('token');
      // 显示退出成功提示
      Toast.success(res.msg || '已安全退出登录', 1);
      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        onLogout();
      }, 500);
    } catch (e: any) {
      console.log('退出登录接口异常:', e);
      // 即使接口调用失败，也清除本地token并跳转
      await AsyncStorage.removeItem('token');
      Toast.fail(e.message || '网络错误，但已清除本地登录状态', 1);
      // 延迟跳转
      setTimeout(() => {
        onLogout();
      }, 500);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar
        barStyle="dark-content"
        backgroundColor="#fff"
        translucent={true}
      />
      {/* 顶部固定区域 */}
      <View style={styles.headerContainer}>
        <View style={styles.header}>
          <Text style={styles.title}>工单进度</Text>
          <TouchableOpacity onPress={handleLogout} style={styles.headerRightBtn}>
            <Image source={outlogin} style={{ width: 24, height: 24, tintColor: '#333' }} />
          </TouchableOpacity>
        </View>
      </View>

      <View style={styles.content}>
        {/* 搜索区域 */}
        <View style={styles.searchContainer}>
          <View style={styles.searchRow}>
            <View style={styles.inputContainer}>
              <TextInput
                style={styles.searchInput}
                placeholder="请输入工单号或者产品编码"
                value={keyword}
                onChangeText={setKeyword}
                placeholderTextColor="#999"
              />
              {keyword.length > 0 && (
                <TouchableOpacity
                  style={styles.clearButton}
                  onPress={() => setKeyword('')}
                >
                  <Text style={styles.clearButtonText}>×</Text>
                </TouchableOpacity>
              )}
            </View>
            <TouchableOpacity
              style={[styles.searchButton, loading && styles.searchButtonDisabled]}
              onPress={() => searchWorkOrders(keyword)}
              disabled={loading}
            >
              <Text style={styles.searchButtonText}>搜索</Text>
            </TouchableOpacity>
          </View>
        </View>

        {/* 工单列表展示 */}
        {!hasSearched ? (
          <View style={styles.emptyContainer}>
            <Image source={zwsj} style={styles.emptyImage} />
            <Text style={styles.emptyText}>请输入工单号或者产品编码</Text>
          </View>
        ) : (
          <FlatList
            data={workOrders}
            renderItem={renderWorkOrderItem}
            keyExtractor={(item, index) => item.id || item.work_order_id || index.toString()}
            style={styles.listContainer}
            refreshControl={
              <RefreshControl
                refreshing={refreshing}
                onRefresh={onRefresh}
                colors={['#007AFF']}
                tintColor="#007AFF"
              />
            }
            onEndReached={onLoadMore}
            onEndReachedThreshold={0.1}
            ListFooterComponent={renderFooter}
            ListEmptyComponent={
              <View style={styles.emptyContainer}>
                <Image source={zwsj} style={styles.emptyImage} />
                <Text style={styles.emptyText}>暂无工单数据</Text>
              </View>
            }
            contentContainerStyle={workOrders.length === 0 ? styles.listEmptyContent : undefined}
            showsVerticalScrollIndicator={true}
            removeClippedSubviews={true}
            maxToRenderPerBatch={10}
            windowSize={10}
            initialNumToRender={10}
            getItemLayout={(data, index) => ({
              length: 200, // 估算每个item的高度
              offset: 200 * index,
              index,
            })}
          />
        )}
      </View>

      {/* 图片全屏预览Modal */}
      <Modal
        visible={imagePreviewVisible}
        transparent={true}
        animationType="fade"
        onRequestClose={closeImagePreview}
      >
        <View style={styles.modalOverlay}>
          <TouchableOpacity
            style={styles.modalBackground}
            activeOpacity={1}
            onPress={closeImagePreview}
          >
            <TouchableOpacity
              style={styles.imageContainer}
              activeOpacity={1}
              onPress={closeImagePreview} // 点击图片也关闭预览
            >
              <Image
                source={previewImageUrl ? { uri: previewImageUrl } : zwtp}
                style={styles.previewImage}
                resizeMode="contain"
              />
            </TouchableOpacity>
          </TouchableOpacity>
        </View>
      </Modal>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  headerContainer: {
    backgroundColor: '#fff',
    paddingTop: getStatusBarHeight(),
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    height: 50,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
    backgroundColor: '#fff',
    position: 'relative',
    zIndex: 10,
  },
  title: {
    fontSize: 22,
    fontWeight: 'bold',
    alignSelf: 'center',
    color: '#333',
  },
  headerRightBtn: {
    position: 'absolute',
    right: 16,
    top: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 8,
  },
  content: {
    flex: 1,
    padding: 10,
  },
  searchContainer: {
    marginBottom: 10,
  },
  searchRow: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
  },
  searchInput: {
    flex: 1,
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 6,
    padding: 10,
    paddingRight: 35,
    backgroundColor: '#fff',
    height: 44,
  },
  clearButton: {
    position: 'absolute',
    right: 8,
    top: 0,
    bottom: 0,
    justifyContent: 'center',
    padding: 8,
  },
  clearButtonText: {
    color: '#999',
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
    width: 20,
    height: 20,
    lineHeight: 20,
  },
  searchButton: {
    backgroundColor: '#007AFF',
    paddingHorizontal: 18,
    height: 44,
    borderRadius: 6,
    justifyContent: 'center',
    marginLeft: 8,
  },
  searchButtonDisabled: {
    backgroundColor: '#ccc',
  },
  searchButtonText: {
    color: '#fff',
    fontWeight: 'bold',
  },
  mainText: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#333',
    textAlign: 'center',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  emptyImage: {
    width: 160,
    height: 160,
    marginBottom: 16,
  },
  emptyText: {
    fontSize: 16,
    color: '#888',
    textAlign: 'center',
  },
  listContainer: {
    flex: 1,
  },
  listTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 16,
  },
  listItem: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 16,
    marginBottom: 8,
    borderWidth: 1,
    borderColor: '#eee',
  },
  itemText: {
    fontSize: 14,
    color: '#333',
    marginBottom: 4,
  },
  itemHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 8,
  },
  itemLabel: {
    fontSize: 14,
    color: '#333',
    fontWeight: 'bold',
    width: 80,
  },
  itemValue: {
    fontSize: 14,
    color: '#333',
    flex: 1,
  },
  itemMiddle: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 16,
  },
  productImage: {
    width: 60,
    height: 60,
    borderRadius: 4,
    marginRight: 12,
  },
  itemInfo: {
    flex: 1,
  },
  itemRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 4,
  },
  expandButton: {
    alignItems: 'center',
    paddingVertical: 8,
  },
  expandText: {
    color: '#007AFF',
    fontSize: 14,
    fontWeight: 'bold',
  },
  loadingMore: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 16,
  },
  loadingText: {
    fontSize: 14,
    color: '#888',
    marginLeft: 8,
  },
  batchContainer: {
    marginTop: 12,
    paddingTop: 12,
    borderTopWidth: 1,
    borderTopColor: '#eee',
  },
  batchTitle: {
    fontSize: 14,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 8,
  },
  batchItem: {
    backgroundColor: '#f8f8f8',
    padding: 8,
    borderRadius: 4,
    marginBottom: 6,
  },
  batchText: {
    fontSize: 12,
    color: '#666',
    marginBottom: 2,
  },
  noBatchText: {
    fontSize: 12,
    color: '#999',
    fontStyle: 'italic',
    textAlign: 'center',
    paddingVertical: 8,
  },
  batchRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 2,
  },
  batchLabel: {
    fontSize: 12,
    color: '#666',
    fontWeight: 'bold',
  },
  batchValue: {
    fontSize: 12,
    color: '#333',
    flexShrink: 1,
    textAlign: 'right',
  },
  // 图片预览相关样式
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.9)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  modalBackground: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    width: '100%',
    height: '100%',
  },
  imageContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    width: '100%',
    height: '100%',
  },
  previewImage: {
    width: Dimensions.get('window').width,
    height: Dimensions.get('window').height,
  },
  listEmptyContent: {
    flexGrow: 1,
  },
});

export default WorkFlowScreen; 
